Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
How to filter a multiple array bye value[0] of each line?

I would like to filter a multiple array in JS by the value[0] of each line. In my next array, there are several "visiteur", "paris", "monaco" and I want to have juste one of each. Any idea ?

My array :

0: ['firstname', 'id']

1: ['FootContact Team', '1']

2: ['Cergy Pontoise Football Club', '2']

3: ['visiteur', '42']

4: ['visiteur', '43']

5: ['visiteur', '44']

6: ['monaco', '45']

7: ['monaco', '46']

8: ['paris', '47']

9: ['paris', '48']

I expect this :

0: ['firstname', 'id']

1: ['FootContact Team', '1']

2: ['Cergy Pontoise Football Club', '2']

3: ['visiteur', '42']

6: ['monaco', '45']

8: ['paris', '47']

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

let listOfUsers = [['toto', 1], ['titi', 2],['titi', 5], ['visiteur',3], ['visiteur', 4]];
let filtered = {};
listOfUsers = listOfUsers.filter((user) => {
    let name = user[0];
    if (!filtered[name]) {
        // set flag and return true since it's the first happening
        return filtered[name] = true;
    }
});
console.log(listOfUsers);
about 4 years ago · Juan Pablo Isaza Report

0

Generically speaking, you want to keep an element in your array if it did not show up beforehand.

  • input.filter((element, index, array) => ...) uses the additional filter arguments
  • array.slice(0, index) contains the array elements smaller than the current index
  • some(element2 => (element[0] === element2[0])) returns true if at least one prior element is identical wrt. to the first element

let input = [
    ['firstname', 'id'],
    ['FootContact Team', '1'],
    ['Cergy Pontoise Football Club', '2'],
    ['visiteur', '42'],
    ['visiteur', '43'],
    ['visiteur', '44'],
    ['monaco', '45'],
    ['monaco', '46'],
    ['paris', '47'],
    ['paris', '48'],
]

let expectedOutput = [
    ['firstname', 'id'],
    ['FootContact Team', '1'],
    ['Cergy Pontoise Football Club', '2'],
    ['visiteur', '42'],
    ['monaco', '45'],
    ['paris', '47'],
]

let actualOutput = input.filter((element, index, array) =>  !array.slice(0, index).some(element2 => (element[0] === element2[0])))

console.log(
  JSON.stringify(actualOutput) 
  ===
  JSON.stringify(expectedOutput)
)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!